// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Table,Form,Radio,Tooltip,Tree, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './groupMonthReportDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { RangePicker,MonthPicker } = DatePicker
const { Option } = Select;
const { TextArea } = Input;
const { TreeNode } = Tree
const { Column, ColumnGroup } = Table;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const groupMonthReportDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {monthInitType,butShow,expandedKeys,autoExpandParent,treeData, infoData,query, actionType, btnLoading,loading } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };
  const formItemLayoutPro1 = {
    labelCol: { span: 2 },
    wrapperCol: { span: 20 },
  };
   
  const columns = [
    {
      title: '统计月份', dataIndex: 'month', key: 'month',
      render: function (value, item, index) {
        return item.month
      }
    },
    {
      title: '新供面积（万m²）', dataIndex: 'addAcreage', key: 'addAcreage',
      render: function (value, item, index) {
        return item.addAcreage
      }
    },
    {
      title: '成交面积（万m²）',dataIndex: 'transactionAcreage',key: 'transactionAcreage',
      render: function (value, item, index) {
        return  item.transactionAcreage
      }
    },
    {
      title: '成交均价(元/m²)', dataIndex: 'averagePrice', key: 'averagePrice',
      render: function (value, item, index) {
        return item.averagePrice
      }
    }, 
  ]
  const columns1 = [
    {
      title: '量价齐升', dataIndex: 'value1', key: 'value1',
      render: function (value, item, index) {
        return item.value1
      }
    },
    {
      title: '量升价平/跌', dataIndex: 'value2', key: 'value2',
      render: function (value, item, index) {
        return item.value2
      }
    },
    {
      title: '量平价升/跌',dataIndex: 'value3',key: 'value3',
      render: function (value, item, index) {
        return  item.value3
      }
    },
    {
      title: '量价齐平', dataIndex: 'value4', key: 'value4',
      render: function (value, item, index) {
        return item.value4
      }
    }, 
    {
      title: '量价齐跌', dataIndex: 'value5', key: 'value5',
      render: function (value, item, index) {
        return item.value5
      }
    }, 
    {
      title: '量跌价升/平', dataIndex: 'value6', key: 'value6',
      render: function (value, item, index) {
        return item.value6
      }
    }, 
  ]
   
  const gridProps1 = {
    nameSpace: namespace,
    data: {
      columns: columns1
      ,//已发布的活动不能添加和删除时间段
      pageConfig:{},
      tableData: {total: '',dataSource: query.data.formNumber},
      selectedRowKeys:'',
    },
    scroll: { x: '60%' },
    paginationFlag : false,
    loading
  }



  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
  }
  function txtAreaChange(value, name){
    query.data[name] = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { query}
    })
  }

    // -------------------tree----开始----

    function onExpand(Keys){
      expandedKeys =Keys
      autoExpandParent = false
  
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {expandedKeys,autoExpandParent}
      })
    }
    
    function onSelectTree(selectedKeys,info) {
      if(info.node.props.pos.length==7||info.node.props.pos.length==8){
        query.cityId = info.node.props.eventKey
        query.cityName = info.node.props.title
        query.areaId = ''
        query.areaName = ''
      }
      if(info.node.props.pos.length==5||info.node.props.pos.length==6){
        query.areaId = info.node.props.eventKey
        query.areaName = info.node.props.title
        query.cityId = ''
        query.cityName = ''
      }
      if(info.node.props.pos.length==3){
        query.cityId = ''
        query.cityName = ''
        query.areaId = ''
        query.areaName = ''
      }
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {query}
      })
      dispatch({
        type: `${namespace}/graphData`,
        payload: {}
      })
    }

      //树的重装
  function renderTreeNodes(data){
    if(data.length>0){
      return data.map(item => {
        if (item.children) {
          return (
            <TreeNode title={item.title} key={item.key}>
              {renderTreeNodes(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode title={item.title} key={item.key}/>;
      });
    }
  }

  function reasonChange(value, name,id){
    for(var item of infoData){
      if(item.id == id){
        item.reason = value
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {infoData}
    })
  }
  function tabShowFun(){
    butShow = false
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {butShow}
    })
  }
  function editFun(id,reason){
    dispatch({
      type: `${namespace}/updateReason`,
      payload: {id:id,reason:reason}
    })
  }
  
  function getInfo(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/monthInit`,
          payload: {}
        })
        form.resetFields()
      }
    })
  }
  function submit(type){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {type:type}
        })
      }
    })
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check'|| monthInitType==false} type='primary' onClick={e => submit('保存')} loading={btnLoading}>保存</Button>
        <Button disabled={actionType == 'check'|| monthInitType==false} type='primary' onClick={e => submit('提交')} loading={loading}>发布</Button>
      </div>
      <div>
        <div style={{textAlign: 'center',fontWeight: 600,fontSize: '18px',lineHeight: '46px',marginBottom: '20px'}}>集团月报新增</div>
        <div style={{color: 'red',paddingLeft: '4%'}}>注：修改统计月份后，必须点击获取月报数据按钮生成新数据！</div>
        <Row>
          <Col span={12} style={{position: 'relative'}}>
            <FormItem label='统计月份'  {...formItemLayoutPro}>
              {getFieldDecorator('month', {
                rules: [{
                  required: true,  message: '请选择统计月份'
                }],
                initialValue: query.month ? moment(query.month, 'YYYY-MM-DD') : null
              })(
                <MonthPicker disabled={actionType != 'add'} onChange={(e, val) => inputChange(val, 'month')} placeholder="请选择统计月份" />
              )}
            </FormItem>
            <Button disabled={actionType == 'check'}  onClick={e => getInfo()} style={{position: 'absolute',right:'8%',top:4,zIndex:99}}  type='primary'>获取月报数据</Button>
          </Col>
          <Col span={12}>
            <FormItem label='月报标题'  {...formItemLayoutPro}>
              {getFieldDecorator('title', {
                rules: [{
                  required: true, whitespace: true, message: '请输入月报标题'
                }],
                initialValue: query.title
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入月报标题'  onChange={(e) => { inputChange(e.target.value, 'title') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <div className={cx('parting-line')}>月报摘要分析</div>
        <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="住宅-月报摘要结论">
              {getFieldDecorator('residentialConclusion', {
                initialValue: query.data.residentialConclusion,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'residentialConclusion')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="库存-月报摘要结论">
              {getFieldDecorator('inventoryConclusion', {
                initialValue: query.data.inventoryConclusion,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'inventoryConclusion')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="土地-月报摘要结论">
              {getFieldDecorator('landConclusion', {
                initialValue: query.data.landConclusion,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'landConclusion')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="商品住宅市场供应">
              {getFieldDecorator('supply', {
                initialValue: query.data.supply,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'supply')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="商品住宅市场成交">
              {getFieldDecorator('clinch', {
                initialValue: query.data.clinch,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'clinch')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
         <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="商品住宅市场库存">
              {getFieldDecorator('inventory', {
                initialValue: query.data.inventory,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'inventory')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
         <Row>
          <Col span={24}>
          <FormItem {...formItemLayoutPro1}
              label="土地市场">
              {getFieldDecorator('land', {
                initialValue: query.data.land,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(
              <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'land')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
        <div>
          <div className={cx('parting-line')}>我司进驻城市量价走势分析</div>
          <Row>
            <Col span={24}>
            <FormItem {...formItemLayoutPro1}
                label="分析结果">
                {getFieldDecorator('analysisResult', {
                  initialValue: query.data.analysisResult,
                  rules: [
                    { required: false, whitespace: true, message: '', },
                  ],
                })(
                <TextArea disabled={actionType == 'check'}  onChange={e=>{txtAreaChange(e.target.value,'analysisResult')}}></TextArea>
                )}
              </FormItem>
            </Col>
          </Row>
          <div style={{padding: '0 40px'}}>
            <Grid {...gridProps1}/>
          </div>
          <div style={{padding: '0 40px'}}>
             <Row>
             {query.data.formList == undefined ?null:query.data.formList.map((item,index)=>{
               return (<Col key={index} span={8} style={{paddingRight: '20px',paddingTop: '20px'}}>
                          <div  className={styles.individuation}>
                              <Table dataSource={item.data}  scroll={{ y: item.data.length > 10 && 360 }} pagination={false} >
                                <ColumnGroup title={item.title}>
                                  <Column title="城市" dataIndex="city" key="city" width={80}/>
                                  <Column title="成交面积环比" dataIndex="acreageRatio" key="acreageRatio" width={120} 
                                  sorter = {(a, b) => a.acreageRatio - b.acreageRatio}
                                  render={(text, record) => (
                                    <span>
                                      {text + '%'}
                                    </span>
                                  )}/>
                                  <Column title="成交均价环比" dataIndex="averageRatio" key="averageRatio" width={120} 
                                  sorter = {(a, b) => a.averageRatio - b.averageRatio}
                                  render={(text, record) => (
                                    <span>
                                      {text + '%'}
                                    </span>
                                  )}/>
                                </ColumnGroup>
                              </Table>
                          </div>
                      </Col>)
                 })}
              </Row>
          </div>
        </div>        
      </div>
      <div style={{padding: '0 40px'}}>
        <div className={cx('parting-line')} style={{margin: 0}}>区域市场情况</div>
          <Row>
            <Col span={4} className={styles.gridConter}>
              <div  className={styles.treeBox}>
                  <Tree
                    checkable={false}
                    onExpand={onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onSelect={onSelectTree}
                  >
                    {renderTreeNodes(treeData)}
                  </Tree>
              </div>
            </Col>
            <Col span={20} className={styles.gridConter} style={{overflowY:'scroll',maxHeight:'564px'}}>
              {infoData == undefined ?null:infoData.map((item,index)=>{
               return (<div style={{borderBottom: '2px solid #e5e5e5',margin:'0 20px',padding: '20px 0'}} key={index}>
                        <Row>
                          <Col span={11}>
                              <ReactEcharts option={item.option}></ReactEcharts>
                          </Col>
                          <Col span={1}></Col>
                          <Col span={12}>
                            <Table columns={columns} dataSource={item.data} pagination={false}/>
                          </Col>
                        </Row>
                        <div><div style={{margin:'12px 0'}}>{item.title.split("量")[0]}商品住宅成交：</div>{item.quantityRatio}成交面积约 {item.transactionAcreage} 万m²，环比{item.acreageRatio>0?"上升":"下降"} {item.acreageRatio} %，成交均价 {item.averagePrice} 元/m²，环比{item.averageRatio>0?"上升":"下降"} {item.averageRatio} %。</div>
                        <div>
                        <div style={{margin:'12px 0'}}>理由说明：</div>
                          <TextArea rows={4} style={{width:'92%',marginRight:'12px'}} disabled={butShow==false?false:true} value={item.reason}  onChange={e=>{reasonChange(e.target.value,'reason',item.id)}}></TextArea>
                          {butShow==true&&<Button onClick={e => tabShowFun()} disabled={actionType == 'check'} type='primary'>{'修改'}</Button>}
                          {butShow==false&&<Button onClick={e => editFun(item.id,item.reason)} disabled={actionType == 'check'} type='primary'>{'保存'}</Button>}
                        </div>
                        <div style={{marginTop:'12px'}}>数据来源：{item.dataSources}</div>
                      </div>)
              })}
            </Col>
          </Row>       
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(groupMonthReportDetailView))